# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1020': {
        #  信付 快捷 ？ 3-3000 dwc
        'API_KEY': 'tiwjei09BW982UYuweyre779hleD82shfew',
        'gateway': 'http://106.13.5.172:3333/order.html',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def gen_order_sign(d, key):
    s = '{}{}{}{}{}{}{}{}'.format(
        d['amount'], d['mechno'], d['notifyurl'], d['orderip'], d['orderno'], d['paytime'], d['paytype'], key
    )
    _LOGGER.info("xinfupay create sign string: %s", s)
    return generate_sign(s)


def gen_verify_sign(d, key):
    s = '{}{}{}{}{}{}{}'.format(
        d['amount'], d['orderno'], d['paytime'], d['paytype'], d['platform_number'], d['result'], key
    )
    return generate_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = gen_verify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("xinfupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipayh5':
        return '1'
    elif service == 'alipayscan':
        return '2'
    elif service == 'wechath5':
        return '3'
    elif service == 'wechatscan':
        return '4'
    elif service == 'bank':  # 网银
        return '5'
    elif service == 'unionwap':  # 银联wap
        return '6'
    elif service == 'unionscap':  # 银联扫码
        return '7'
    elif service == 'unionquick':  # 快捷
        return '8'
    return '2'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='get'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mechno', app_id),
        ('orderip', _get_device_ip(service)),
        ('amount', str(int(pay_amount * 100))),
        ('ext', '0'),
        ('notifyurl', '{}/pay/api/{}/xinfupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('returl', '{}/pay/api/{}/xinfupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('orderno', str(pay.id)),
        ('paytype', _get_pay_type(service)),
        ('paytime', int(time.time())),
    ))
    parameter_dict['sign'] = gen_order_sign(parameter_dict, api_key)
    _LOGGER.info("xinfupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['orderno'])
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    mechsecret = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("xinfupay notify data: %s, order_id is: %s", data, data['orderno'])
    verify_notify_sign(data, mechsecret)
    pay_id = data['orderno']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('xinfupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['result'])
    trade_no = data['platform_number']
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 100:成功, 非100:失败
    if trade_status == '100':
        _LOGGER.info('xinfupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
